﻿<%@ webhandler Language="C#" class="Upload" %>

/**
 * KindEditor ASP.NET
 *
 * 本ASP.NET程序是演示程序，建议不要直接在实际项目中使用。
 * 如果您确定直接使用本程序，使用之前请仔细确认相关安全设置。
 *
 */

using System;
using System.Collections;
using System.Web;
using System.IO;
using System.Globalization;
using LitJson;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Web.Security;
using System.Configuration;
using BLL.Common;


public class Upload : IHttpHandler,IRequiresSessionState
{
	private HttpContext context;
    //图片 最大文件大小
    private string imageMaxSize = ConfigurationManager.AppSettings["imageMaxSize"];//3000000;
    //图片 最大文件大小
    private string flashMaxSize = ConfigurationManager.AppSettings["flashMaxSize"];//5000000;
    //图片最小宽度
    private string widthSmall = ConfigurationManager.AppSettings["widthSmall"];
    //图片最大宽度
    private string widthBig = ConfigurationManager.AppSettings["widthBig"];

    private const int NormalWidth = 480;
    private const int NormalHeight = 0;
    private const int PDFWidth = 360;
    private const int PDFHeight = 0;
    private const int MobileWidth = 120;
    private const int MobileHeight = 0;       
    
	public void ProcessRequest(HttpContext context)
	{
		String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);
		
		//文件保存目录路径
        String dirPath = string.Empty;

		//文件保存目录URL
        String saveUrl = string.Empty;

		//定义允许上传的文件扩展名
		Hashtable extTable = new Hashtable();
		extTable.Add("image", "gif,jpg,jpeg,png,bmp");
		extTable.Add("flash", "swf,flv");
		extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
		extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,pdf,js");

		//最大文件大小
		this.context = context;

		HttpPostedFile imgFile = context.Request.Files["imgFile"];
		if (imgFile == null ||string.IsNullOrEmpty(imgFile.FileName.Trim()))
		{
            //showError("请选择文件。");
            showError(BLL.Common.Language.LanguageHelper.GetLabel("KindEditor.ServerErrMsg1", EMPower.Enum.LanguageCode.Chinese_PRC));
		}
        string url = string.Empty;
        
        if (System.Web.HttpContext.Current.Session["url"] != null)
        {
            url = System.Web.HttpContext.Current.Session["url"].ToString();
        }
    

       

        context.Application["thisPageUrl"] = null;

        //if (url != null && url.Length > 0)
        //{
        //    dirPath = UploadResource.GetPath(BizResourceType.LiveChatResource, BizResourceAccess.Upload);
        //    saveUrl = UploadResource.GetPath(BizResourceType.LiveChatResource, BizResourceAccess.Display);
        //}
        //else
        //{
        //    if (System.Web.HttpContext.Current.Session["url"] != null)
        //    {
        //        string insertPageUrl = System.Web.HttpContext.Current.Session["url"] as string;
        //        if (insertPageUrl.IndexOf("HomeWork") > 1)
        //        {
        //            dirPath = UploadResource.GetPath(BizResourceType.HomeWorkResource, BizResourceAccess.Upload);
        //            saveUrl = UploadResource.GetPath(BizResourceType.HomeWorkResource, BizResourceAccess.Display);
        //        }
        //    }
        //    else
        //    {
        //        dirPath = UploadResource.GetPath(BizResourceType.TopicResource, BizResourceAccess.Upload);
        //        saveUrl = UploadResource.GetPath(BizResourceType.TopicResource, BizResourceAccess.Display);
        //    }
        //}

        if (System.Web.HttpContext.Current.Session["url"] != null)
        {
            if (url.ToLower().IndexOf("memberrelation") > -1)
            {
                dirPath = UploadResource.GetPath(BizResourceType.MemberRelationResource, BizResourceAccess.Upload);
                saveUrl = UploadResource.GetPath(BizResourceType.MemberRelationResource, BizResourceAccess.Display);
            }

            else if (url.ToLower().IndexOf("policy") > -1)
            {
                dirPath = UploadResource.GetPath(BizResourceType.PolicyPagerResource, BizResourceAccess.Upload);
                saveUrl = UploadResource.GetPath(BizResourceType.PolicyPagerResource, BizResourceAccess.Display);
            }

            else if (url.ToLower().IndexOf("user") > -1)
            {
                dirPath = UploadResource.GetPath(BizResourceType.UserResource, BizResourceAccess.Upload);
                saveUrl = UploadResource.GetPath(BizResourceType.UserResource, BizResourceAccess.Display);
            }
            else if (url.ToLower().IndexOf("personalinfomanage") > -1)
            {
                dirPath = UploadResource.GetPath(BizResourceType.FamousRegionResource, BizResourceAccess.Upload);
                saveUrl = UploadResource.GetPath(BizResourceType.FamousRegionResource, BizResourceAccess.Display);
            }         
        }
    
  
        string dirName = context.Request.QueryString["dir"];   //上传类型
        string fileName = imgFile.FileName;                     //文件名
        string fileExt = Path.GetExtension(fileName).ToLower();
        string newFileName = string.Empty;

        //创建文件夹
        if (dirPath.LastIndexOf('/') < dirPath.Length - 1)
        {
            dirPath += "/";
        }
        if (saveUrl.LastIndexOf('/') < saveUrl.Length - 1)
        {
            saveUrl += "/";
        } 
        
        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
            //showError("上传目录不存在。");
        }
        
        if (!extTable.ContainsKey(dirName))
        {
            //showError("目录名不正确。");
            showError(BLL.Common.Language.LanguageHelper.GetLabel("KindEditor.ServerErrMsg2", EMPower.Enum.LanguageCode.Chinese_PRC));
        }
        //判断扩展名
        if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
        {
            //showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((string)extTable[dirName]) + "格式。");
            showError(string.Format(BLL.Common.Language.LanguageHelper.GetLabel("KindEditor.ServerErrMsg3", EMPower.Enum.LanguageCode.Chinese_PRC), (string)extTable[dirName]));
        }
        
        //图片处理上传
        if ("image".Equals(dirName.ToLower()))
        {
            uploadImage(imgFile, extTable, dirPath, fileExt, out newFileName);
        }
        
        //其它上传
        if ("flash".Equals(dirName.ToLower()) || "media".Equals(dirName.ToLower()) || "file".Equals(dirName.ToLower()))
        {
            saveFlash(imgFile, extTable, dirPath, fileExt, out newFileName);
        }
        //上传显示
        string fileUrl = saveUrl + newFileName;
		Hashtable hash = new Hashtable();
		hash["error"] = 0;
		hash["url"] = fileUrl;
		context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
		context.Response.Write(JsonMapper.ToJson(hash));
		context.Response.End();
	}

	private void showError(string message)
	{
		Hashtable hash = new Hashtable();
		hash["error"] = 1;
		hash["message"] = message;
		context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
		context.Response.Write(JsonMapper.ToJson(hash));
		context.Response.End();
	}

	public bool IsReusable
	{
		get
		{
			return true;
		}
    }

    #region 私有方法
    
    
    //上传图片
    private void uploadImage(HttpPostedFile imgFile, Hashtable extTable, string dirPath, string fileExt,out string newFileName)
    {

        //图片宽判断
        int size = 0;
        if (!int.TryParse(imageMaxSize, out size))
        {
            size =3000000;
        }

        if (imgFile.InputStream == null || imgFile.InputStream.Length > size)
        {
            //showError("上传文件大小超过限制。");
            showError(BLL.Common.Language.LanguageHelper.GetLabel("KindEditor.ServerErrMsg4", EMPower.Enum.LanguageCode.Chinese_PRC));
        }

        //图片宽判断
        int smallWidth = 0;
        if (!int.TryParse(widthSmall, out smallWidth))
        {
            smallWidth = 0;
        }

        int bigWidth = 0;
        if (!int.TryParse(widthBig, out bigWidth))
        {
            bigWidth = 0;
        }
        System.Drawing.Image abcImg = System.Drawing.Image.FromStream(imgFile.InputStream);
        if (smallWidth > 0 && smallWidth > abcImg.Width)
        {
            //showError("上传文件宽度应大于" + smallWidth.ToString() + "。");
            showError(string.Format(BLL.Common.Language.LanguageHelper.GetLabel("KindEditor.ServerErrMsg5", EMPower.Enum.LanguageCode.Chinese_PRC), smallWidth.ToString()));
        }
        if (bigWidth > 0 && bigWidth < abcImg.Width)
        {
            //showError("上传文件宽度应小于" + bigWidth.ToString() + "。");
            showError(string.Format(BLL.Common.Language.LanguageHelper.GetLabel("KindEditor.ServerErrMsg6", EMPower.Enum.LanguageCode.Chinese_PRC), bigWidth.ToString()));
        }
        abcImg.Clone();
        abcImg.Dispose();

        string fileNameTemp = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
        String filePath = dirPath + fileNameTemp;

        imgFile.SaveAs(filePath);
        imgFile = null;
        //田富永Add
        //ImageHandle image = new ImageHandle(filePath);
        ImageHandle image = new ImageHandle(filePath, EMPower.Enum.LanguageCode.Chinese_PRC);
        //newFileName = DateTime.Now.AddMilliseconds(1).ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
        //string savePath = dirPath + newFileName;
        //image.GetCutImg(480, 0, savePath, false);
        string savePath = string.Empty;
        if (dirPath.ToLower().IndexOf("index") == -1)
        {
            //ExportForPDF
            if (!Directory.Exists(dirPath + BizImgSize.ImageForPDF.ToString()))
            {
                Directory.CreateDirectory(dirPath + BizImgSize.ImageForPDF.ToString());
            }
            newFileName = BizImgSize.ImageForPDF.ToString() + "/" + fileNameTemp;
            savePath = dirPath + newFileName;
            image.GetCutImg(PDFWidth, PDFHeight, savePath, false);

            //Mobile
            if (!Directory.Exists(dirPath + BizImgSize.ImageForMobile.ToString()))
            {
                Directory.CreateDirectory(dirPath + BizImgSize.ImageForMobile.ToString());
            }
            newFileName = BizImgSize.ImageForMobile.ToString() + "/" + fileNameTemp;
            savePath = dirPath + newFileName;
            image.GetCutImg(MobileWidth, MobileHeight, savePath, false);

            //Normal
            if (!Directory.Exists(dirPath + BizImgSize.ImageForNormal.ToString()))
            {
                Directory.CreateDirectory(dirPath + BizImgSize.ImageForNormal.ToString());
            }
            newFileName = BizImgSize.ImageForNormal.ToString() + "/" + fileNameTemp;
            savePath = dirPath + newFileName;
            image.GetCutImg(NormalWidth, NormalHeight, savePath, false);
            File.Delete(filePath);
        }
        else
        {
            newFileName = fileNameTemp;
        }   
        
    }


    //上传其它 falash movie doc
    private void saveFlash(HttpPostedFile imgFile, Hashtable extTable, string dirPath, string fileExt, out string newFileName)
    {

        int size = 0;
        if (!int.TryParse(flashMaxSize, out size))
        {
            size = 500000000;
        }
        if (imgFile.InputStream == null || imgFile.InputStream.Length > size)
        {
            //showError("上传文件大小超过限制。");
            showError(BLL.Common.Language.LanguageHelper.GetLabel("KindEditor.ServerErrMsg4", EMPower.Enum.LanguageCode.Chinese_PRC));
        }
    
        newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
        string filePath = dirPath + newFileName;

        imgFile.SaveAs(filePath);
    }


    #endregion
}
